from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from django.utils.deconstruct import deconstructible


@deconstructible()
class FastDFSStorage(Storage):

    def __init__(self, conf_client=None, base_url=None):
        if conf_client is None:
            conf_client = settings.CONFIG
        self.conf_client = conf_client
        if base_url is None:
            base_url = settings.BASE_URL
        self.base_url = base_url

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content):
        client = Fdfs_client(self.conf_client)
        ret = client.upload_by_buffer(content.read())
        # 判断文件是否上传成功
        if ret.get("Status") != "Upload successed.":
            raise Exception("upload file failed")
        file_name = ret.get("Remote file_id")
        return file_name

    # 构造图片访问链接
    def url(self, name):
        return self.base_url + name

    def exists(self, name):
        return False